<template>
  <div class="wechat-container">
    
    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-input">
        <i class="search-icon">🔍</i>
        <input 
          v-model="searchText" 
          type="text" 
          placeholder="请输入共享电源名称"
          @keyup.enter="handleSearch"
        />
        <button class="search-btn" @click="handleSearch">搜索</button>
      </div>
      
      <!-- 位置状态指示器 -->
      <div class="location-status">
        <div v-if="locationStatus === 'loading'" class="status-item loading">
          <i class="status-icon">🔄</i>
          <span>正在获取位置...</span>
        </div>
        <div v-else-if="locationStatus === 'success'" class="status-item success">
          <i class="status-icon">📍</i>
          <span>位置获取成功</span>
          <span v-if="locationAccuracy" class="accuracy-info">(精度: {{ Math.round(locationAccuracy) }}米)</span>
          <button class="refresh-location-btn" @click="refreshCurrentLocation">🔄</button>
        </div>
        <div v-else-if="locationStatus === 'error'" class="status-item error">
          <i class="status-icon">⚠️</i>
          <span>位置获取失败，使用默认位置</span>
          <button class="refresh-location-btn" @click="refreshCurrentLocation">重试</button>
        </div>
        <div v-else-if="locationStatus === 'denied'" class="status-item denied">
          <i class="status-icon">🔒</i>
          <span>位置权限被拒绝，使用默认位置</span>
          <button class="refresh-location-btn" @click="refreshCurrentLocation">重试</button>
        </div>
      </div>
    </div>

    <!-- 地图容器 -->
    <div class="map-container">
      <div id="amap-container" class="amap-container"></div>
    </div>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
      <div class="nav-item active" :class="{ active: currentTab === 'home' }" @click="switchTab('home')">
        <i class="el-icon-house"></i>
        <span>首页</span>
      </div>
      <div class="nav-item" :class="{ active: currentTab === 'scan' }" @click="switchTab('scan')">
        <i class="el-icon-camera"></i>
        <span>扫码用电</span>
      </div>
      <div class="nav-item " :class="{ active: currentTab === 'mine' }" @click="switchTab('mine')">
        <i class="el-icon-user"></i>
        <span>我的</span>
      </div>
    </div>

    <!-- 搜索结果列表 -->
    <div v-if="searchResults.length > 0" class="search-results">
      <div class="results-header">
        <span>搜索结果 ({{ searchResults.length }})</span>
        <i class="close-results" @click="closeSearchResults">×</i>
      </div>
      <div class="results-list">
        <div 
          v-for="(result, index) in searchResults" 
          :key="index"
          class="result-item"
          @click="selectLocation(result)"
        >
          <div class="result-name">{{ result.name }}</div>
          <div class="result-address">{{ result.address }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AmapUtils from '@/utils/amap'
import { listStation } from '@/api/station/station'
import { Message, Loading } from 'element-ui'
import { createPayOrder, getJSSDKConfig, createRefund } from '@/api/wechat'

export default {
  name: 'WechatIndex',
  data() {
    return {
      searchText: '',
      currentTab: 'home',
      showFilterPanel: false,
      filterArea: '',
      filterType: '',
      searchResults: [],
      map: null,
      markers: [],
      locationStatus: 'loading', // 位置状态：loading, success, error, denied
      currentLocation: null, // 当前位置信息
      locationAccuracy: null, // 位置精度信息
      locationWatchId: null, // 位置监听器ID
      showLocationPanel: true // 是否显示位置信息面板
    }
  },
  mounted() {
    this.initMap()
    this.initWechatJSSDK()
    // 获取当前位置并设置为地图中心
    this.getCurrentLocation()
  },
  beforeDestroy() {
    // 清理位置监听器
    if (this.locationWatchId) {
      navigator.geolocation.clearWatch(this.locationWatchId)
    }
  },
  methods: {
    // 坐标转换工具：WGS84转GCJ02
    transformWGS84ToGCJ02(lng, lat) {
      // 地球长半轴
      const a = 6378245.0
      // 地球偏心率平方
      const ee = 0.00669342162296594323
      
      let dLat = this.transformLat(lng - 105.0, lat - 35.0)
      let dLng = this.transformLng(lng - 105.0, lat - 35.0)
      
      const radLat = lat / 180.0 * Math.PI
      let magic = Math.sin(radLat)
      magic = 1 - ee * magic * magic
      const sqrtMagic = Math.sqrt(magic)
      
      dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * Math.PI)
      dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * Math.PI)
      
      const mgLat = lat + dLat
      const mgLng = lng + dLng
      
      return {
        lng: mgLng,
        lat: mgLat
      }
    },
    
    // 纬度转换
    transformLat(lng, lat) {
      let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng))
      ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0
      ret += (20.0 * Math.sin(lat * Math.PI) + 40.0 * Math.sin(lat / 3.0 * Math.PI)) * 2.0 / 3.0
      ret += (160.0 * Math.sin(lat / 12.0 * Math.PI) + 320 * Math.sin(lat * Math.PI / 30.0)) * 2.0 / 3.0
      return ret
    },
    
    // 经度转换
    transformLng(lng, lat) {
      let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng))
      ret += (20.0 * Math.sin(6.0 * lng * Math.PI) + 20.0 * Math.sin(2.0 * lng * Math.PI)) * 2.0 / 3.0
      ret += (20.0 * Math.sin(lng * Math.PI) + 40.0 * Math.sin(lng / 3.0 * Math.PI)) * 2.0 / 3.0
      ret += (150.0 * Math.sin(lng / 12.0 * Math.PI) + 300.0 * Math.sin(lng / 30.0 * Math.PI)) * 2.0 / 3.0
      return ret
    },

    // 计算两点间距离（米）
    calculateDistance(lat1, lng1, lat2, lng2) {
      const R = 6371000 // 地球半径（米）
      const dLat = (lat2 - lat1) * Math.PI / 180
      const dLng = (lng2 - lng1) * Math.PI / 180
      const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                Math.sin(dLng / 2) * Math.sin(dLng / 2)
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
      return R * c
    },

    // 获取最佳位置（多次定位取平均值）
    async getBestLocation() {
      return new Promise((resolve, reject) => {
        const positions = []
        let attempts = 0
        const maxAttempts = 3
        const minAccuracy = 50 // 最小精度要求（米）
        
        const watchId = navigator.geolocation.watchPosition(
          (position) => {
            const { longitude, latitude, accuracy } = position.coords
            
            // 转换坐标系
            const gcj02 = this.transformWGS84ToGCJ02(longitude, latitude)
            
            positions.push({
              lng: gcj02.lng,
              lat: gcj02.lat,
              accuracy: accuracy,
              timestamp: position.timestamp
            })
            
            attempts++
            
            // 如果精度足够好或者已经尝试了足够次数，就停止
            if (accuracy <= minAccuracy || attempts >= maxAttempts) {
              navigator.geolocation.clearWatch(watchId)
              
              if (positions.length > 0) {
                // 选择精度最好的位置
                const bestPosition = positions.reduce((best, current) => 
                  current.accuracy < best.accuracy ? current : best
                )
                
                resolve({
                  lng: bestPosition.lng,
                  lat: bestPosition.lat,
                  accuracy: bestPosition.accuracy,
                  positions: positions
                })
              } else {
                reject(new Error('无法获取有效位置'))
              }
            }
          },
          (error) => {
            navigator.geolocation.clearWatch(watchId)
            reject(error)
          },
          {
            enableHighAccuracy: true,
            timeout: 15000,
            maximumAge: 0 // 不使用缓存
          }
        )
        
        // 设置超时
        setTimeout(() => {
          navigator.geolocation.clearWatch(watchId)
          if (positions.length > 0) {
            const bestPosition = positions.reduce((best, current) => 
              current.accuracy < best.accuracy ? current : best
            )
            resolve({
              lng: bestPosition.lng,
              lat: bestPosition.lat,
              accuracy: bestPosition.accuracy,
              positions: positions
            })
          } else {
            reject(new Error('定位超时'))
          }
        }, 20000)
      })
    },

    async initWechatJSSDK() {
      window.isWxReady = false
      // 检查是否在微信环境中
      if (typeof wx === 'undefined') {
        console.log('当前不在微信环境中')
        return
      }

      try {
        // 获取当前页面URL
        const currentUrl = window.location.href.split('#')[0];
        
        // 获取JSSDK配置
        const response = await getJSSDKConfig(currentUrl)
        
        if (response.code === 200) {
          const config = response.data
          
          // 配置微信JSSDK
          wx.config({
            debug: false, // 生产环境设为false
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: ['chooseWXPay', 'scanQRCode'] // 需要使用的JS接口列表
          })

          // 配置完成后
          wx.ready(() => {
            console.log('微信JSSDK配置成功')
            window.isWxReady = true
          })

          // 配置失败
          wx.error((res) => {
            console.error('微信JSSDK配置失败:', res)
            this.$message.error('微信环境初始化失败')
          })
        } else {
          console.error('获取JSSDK配置失败:', response.msg)
        }
      } catch (error) {
        console.error('初始化微信JSSDK失败:', error)
      }
    },
    // 初始化地图
    async initMap() {
      try {
        await AmapUtils.initMap('amap-container')
        this.map = AmapUtils.map
      } catch (error) {
          console.error('地图初始化失败:', error)
          Message.error('地图加载失败，请检查网络连接')
      }
    },   
    // 扫码
    scanQRCode() {
      wx.scanQRCode({
        needResult: 1,
        scanType: ['qrCode', 'barCode'],
        success: (result) => {
            window.meterNo = result.resultStr
            this.$router.push('/wechat/recharge')
        },
        fail: (error) => {
            Message.error("扫码失败")
        }
      })
      this.currentTab = 'home'
    },
    // 处理搜索
    async handleSearch() {
      if (!this.searchText.trim()) {
        Message.warning('请输入搜索内容')
        return
      }
      // 显示加载状态
      const loadingInstance = Loading.service({
        lock: true,
        text: '搜索中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      try {          
          const stationList = await listStation({powerName: this.searchText})          
          // 关闭加载状态
          loadingInstance.close()

          // 清除之前的搜索结果
          this.clearSearchResults()

        // 遍历stationList.rows
        if (stationList.rows && stationList.rows.length > 0) {
          // 显示位置处理加载状态
          const positionLoadingInstance = Loading.service({
            lock: true,
            text: `正在处理${stationList.rows.length}个位置...`,
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          
          // 处理第一条记录，设置地图中心
          const firstStation = stationList.rows[0]
          try {
            // 根据installAddress查找经纬度
            const location = await AmapUtils.searchLocationByName(firstStation.installAddress)
            
            // 设置地图中心到第一个位置
            AmapUtils.setCenter(location.lng, location.lat)
            AmapUtils.setZoom(16)
            
            // 添加第一个标记
            const marker = AmapUtils.addMarker({
              lng: location.lng,
              lat: location.lat,
              name: firstStation.powerName,
              address: firstStation.installAddress
            }, {
              title: firstStation.powerName,
              icon: '⚡️'
            })
            
            if (marker) {
              this.markers.push(marker)
            }
            
            // 处理剩余记录
            let successCount = 1 // 第一个已成功
            for (let i = 1; i < stationList.rows.length; i++) {
              const station = stationList.rows[i]
              try {
                const stationLocation = await AmapUtils.searchLocationByName(station.installAddress)
                
                const stationMarker = AmapUtils.addMarker({
                  lng: stationLocation.lng,
                  lat: stationLocation.lat,
                  name: station.powerName,
                  address: station.installAddress
                }, {
                  title: station.powerName,
                  icon: '⚡️'
                })
                
                if (stationMarker) {
                  this.markers.push(stationMarker)
                  successCount++
                }
              } catch (error) {
                console.error(`获取${station.powerName}位置失败:`, error)
              }
            }
            
            // 显示搜索结果
            this.searchResults = stationList.rows.map(station => ({
              name: station.powerName,
              address: station.installAddress
            }))
            
            Message.success(`成功标记${successCount}个位置`)
            
          } catch (error) {
            console.error('获取第一个位置失败:', error)
            Message.error('无法获取位置信息' + error)
          } finally {
            // 关闭位置处理加载状态
            positionLoadingInstance.close()
          }
        } else {
          Message.warning('未找到相关电源设备')
        }
        // Message.success('搜索完成')
      } catch (error) {
        loadingInstance.close()
        console.error('搜索失败:', error)
        Message.error('搜索失败：' + (error.message || '请检查输入内容'))
      }
    },

    // 清除搜索结果
    clearSearchResults() {
      this.searchResults = []
      // 清除之前的标记
      this.markers.forEach(marker => {
        if (marker && marker.setMap) {
          marker.setMap(null)
        }
      })
      this.markers = []
    },

    // 关闭搜索结果
    closeSearchResults() {
      this.searchResults = []
    },

    // 选择位置
    selectLocation(location) {
      AmapUtils.setCenter(location.lng, location.lat)
      AmapUtils.setZoom(18)
      this.searchResults = []
              Message.success(`已定位到 ${location.name}`)
    },

    // 获取当前位置并设置为地图中心
    async getCurrentLocation() {
      if (navigator.geolocation) {
        try {
          // 检查位置权限
          const permission = await this.checkLocationPermission()
          if (permission === 'denied') {
            Message.warning('位置权限被拒绝，使用默认位置')
            this.locationStatus = 'denied'
            this.useDefaultLocation()
            return
          }
          
          // 使用改进的定位方法
          const bestLocation = await this.getBestLocation()
          
          // 设置地图中心到当前位置
          AmapUtils.setCenter(bestLocation.lng, bestLocation.lat)
          
          // 添加当前位置标记
          const currentLocation = {
            name: '当前位置',
            lng: bestLocation.lng,
            lat: bestLocation.lat,
            accuracy: bestLocation.accuracy
          }
          
          // 保存当前位置信息
          this.currentLocation = currentLocation
          this.locationAccuracy = bestLocation.accuracy
          this.locationStatus = 'success'
          
          const marker = AmapUtils.addMarker(currentLocation, {
            title: `当前位置 (精度: ${Math.round(bestLocation.accuracy)}米)`,
            icon: '📍' // 使用emoji表示当前位置
          })
          
          if (marker) {
            this.markers.push(marker)
          }
                    
          console.log('已获取当前位置:', { 
            lng: bestLocation.lng, 
            lat: bestLocation.lat, 
            accuracy: bestLocation.accuracy 
          })
          
          // 显示精度信息
          if (bestLocation.accuracy <= 20) {
            Message.success(`定位成功！精度: ${Math.round(bestLocation.accuracy)}米`)
          } else if (bestLocation.accuracy <= 50) {
            Message.warning(`定位成功，精度一般: ${Math.round(bestLocation.accuracy)}米`)
          } else {
            Message.warning(`定位成功，精度较低: ${Math.round(bestLocation.accuracy)}米`)
          }
          
        } catch (error) {
          console.error('获取当前位置失败:', error)
          Message.warning('获取当前位置失败，尝试使用单次定位')
          
          // 如果改进方法失败，尝试传统方法
          try {
            const position = await this.getCurrentPosition()
            const { longitude, latitude, accuracy } = position.coords
            
            // 转换坐标系
            const gcj02 = this.transformWGS84ToGCJ02(longitude, latitude)
            
            // 设置地图中心到当前位置
            AmapUtils.setCenter(gcj02.lng, gcj02.lat)
            
            // 添加当前位置标记
            const currentLocation = {
              name: '当前位置',
              lng: gcj02.lng,
              lat: gcj02.lat,
              accuracy: accuracy
            }
            
            // 保存当前位置信息
            this.currentLocation = currentLocation
            this.locationAccuracy = accuracy
            this.locationStatus = 'success'
            
            const marker = AmapUtils.addMarker(currentLocation, {
              title: `当前位置 (精度: ${Math.round(accuracy)}米)`,
              icon: '📍'
            })
            
            if (marker) {
              this.markers.push(marker)
            }
            
            Message.success(`定位成功！精度: ${Math.round(accuracy)}米`)
            
          } catch (fallbackError) {
            console.error('传统定位方法也失败:', fallbackError)
            Message.error('获取当前位置失败，使用默认位置')
            this.locationStatus = 'error'
            this.useDefaultLocation()
          }
        }
      } else {
        Message.warning('浏览器不支持地理定位，使用默认位置')
        this.useDefaultLocation()
      }
    },
    // 检查位置权限
    async checkLocationPermission() {
      if (navigator.permissions && navigator.permissions.query) {
        try {
          const result = await navigator.permissions.query({ name: 'geolocation' })
          return result.state
        } catch (error) {
          console.warn('无法检查位置权限:', error)
          return 'unknown'
        }
      }
      return 'unknown'
    },

    // 获取当前位置的Promise包装
    getCurrentPosition() {
      return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(
          resolve,
          reject,
          {
            enableHighAccuracy: true, // 高精度定位
            timeout: 10000, // 10秒超时
            maximumAge: 60000 // 1分钟内的缓存位置
          }
        )
      })
    },

    // 使用默认位置
    useDefaultLocation() {
      const defaultCenter = [118.796877, 32.060255] // 南京市中心
      AmapUtils.setCenter(defaultCenter[0], defaultCenter[1])
      AmapUtils.setZoom(15)
      console.log('使用默认位置:', defaultCenter)
      
    },

    // 刷新当前位置
    async refreshCurrentLocation() {
      this.locationStatus = 'loading'
      
      // 显示刷新位置加载状态
      const refreshLoadingInstance = Loading.service({
        lock: true,
        text: '正在刷新位置...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
        // 清除之前的当前位置标记
        this.clearCurrentLocationMarker()
        
        // 重新获取当前位置
        await this.getCurrentLocation()
        Message.success('位置已刷新')
      } catch (error) {
        console.error('刷新位置失败:', error)
        Message.error('位置刷新失败')
      } finally {
        // 关闭刷新位置加载状态
        refreshLoadingInstance.close()
      }
    },

    // 清除当前位置标记
    clearCurrentLocationMarker() {
      // 找到并清除当前位置标记（绿色标记）
      this.markers = this.markers.filter(marker => {
        if (marker && marker.getTitle && marker.getTitle() === '当前位置') {
          marker.setMap(null)
          return false
        }
        return true
      })
    },

    // 定位到用户位置（手动触发）
    async centerToUserLocation() {
      if (navigator.geolocation) {
        // 显示定位加载状态
        const locationLoadingInstance = Loading.service({
          lock: true,
          text: '定位中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        
        try {
          // 清除之前的当前位置标记
          this.clearCurrentLocationMarker()
          
          // 使用改进的定位方法
          const bestLocation = await this.getBestLocation()
          
          // 设置地图中心到当前位置
          AmapUtils.setCenter(bestLocation.lng, bestLocation.lat)
          AmapUtils.setZoom(16)
          
          // 添加当前位置标记
          const currentLocation = {
            name: '当前位置',
            lng: bestLocation.lng,
            lat: bestLocation.lat,
            accuracy: bestLocation.accuracy
          }
          
          // 保存当前位置信息
          this.currentLocation = currentLocation
          this.locationAccuracy = bestLocation.accuracy
          
          const marker = AmapUtils.addMarker(currentLocation, {
            title: `当前位置 (精度: ${Math.round(bestLocation.accuracy)}米)`,
            icon: '📍'
          })
          
          if (marker) {
            this.markers.push(marker)
          }
          
          // 关闭定位加载状态
          locationLoadingInstance.close()
          
          // 显示精度信息
          if (bestLocation.accuracy <= 20) {
            Message.success(`定位成功！精度: ${Math.round(bestLocation.accuracy)}米`)
          } else if (bestLocation.accuracy <= 50) {
            Message.warning(`定位成功，精度一般: ${Math.round(bestLocation.accuracy)}米`)
          } else {
            Message.warning(`定位成功，精度较低: ${Math.round(bestLocation.accuracy)}米`)
          }
          
        } catch (error) {
          console.error('获取位置失败:', error)
          
          // 如果改进方法失败，尝试传统方法
          try {
            const position = await this.getCurrentPosition()
            const { longitude, latitude, accuracy } = position.coords
            
            // 转换坐标系
            const gcj02 = this.transformWGS84ToGCJ02(longitude, latitude)
            
            // 设置地图中心到当前位置
            AmapUtils.setCenter(gcj02.lng, gcj02.lat)
            AmapUtils.setZoom(16)
            
            // 添加当前位置标记
            const currentLocation = {
              name: '当前位置',
              lng: gcj02.lng,
              lat: gcj02.lat,
              accuracy: accuracy
            }
            
            // 保存当前位置信息
            this.currentLocation = currentLocation
            this.locationAccuracy = accuracy
            
            const marker = AmapUtils.addMarker(currentLocation, {
              title: `当前位置 (精度: ${Math.round(accuracy)}米)`,
              icon: '📍'
            })
            
            if (marker) {
              this.markers.push(marker)
            }
            
            // 关闭定位加载状态
            locationLoadingInstance.close()
            Message.success(`定位成功！精度: ${Math.round(accuracy)}米`)
            
          } catch (fallbackError) {
            // 关闭定位加载状态
            locationLoadingInstance.close()
            console.error('传统定位方法也失败:', fallbackError)
            Message.error('无法获取您的位置，请检查定位权限')
          }
        }
      } else {
        Message.warning('您的浏览器不支持地理定位')
      }
    },

    // 显示筛选面板
    showFilter() {
      this.showFilterPanel = !this.showFilterPanel
    },

    // 应用筛选
    applyFilter() {
      // 这里可以实现筛选逻辑
      this.showFilterPanel = false
              Message.success('筛选条件已应用')
    },

    // 重置筛选
    resetFilter() {
      this.filterArea = ''
      this.filterType = ''
      Message.success('筛选条件已重置')
    },

    // 切换标签页
    switchTab(tab) {
      this.currentTab = tab
      if (tab === 'home') {
        this.$router.push('/wechat/index')
      } else if (tab === 'mine') {
        this.$router.push('/wechat/mine')
      } else if (tab === 'scan') {
        this.scanQRCode()
      } 
    },

    // 关闭位置信息面板
    closeLocationPanel() {
      this.showLocationPanel = false
      console.log('关闭位置信息面板')
    },

    // 返回
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.wechat-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 状态栏样式 */
.status-bar {
  height: 44px;
  background: #000;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  font-size: 14px;
}

.wifi-info {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  padding: 4px 12px;
  border-radius: 20px;
}

.wifi-icon::before {
  content: "📶";
  margin-right: 4px;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.battery {
  width: 24px;
  height: 12px;
  border: 1px solid white;
  border-radius: 2px;
  position: relative;
}

.battery-level {
  height: 100%;
  background: #4CAF50;
  border-radius: 1px;
}

.lightning::before {
  content: "⚡";
  position: absolute;
  right: -8px;
  top: -2px;
  font-size: 10px;
}

/* 头部样式 */
.header {
  background: #1976D2;
  color: white;
  padding: 16px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-center {
  text-align: center;
}

.title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.subtitle {
  margin: 4px 0 0 0;
  font-size: 12px;
  opacity: 0.8;
}

.close-icon, .more-icon {
  font-size: 20px;
  cursor: pointer;
}

/* 搜索栏样式 */
.search-bar {
  background: white;
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.search-input {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 8px;
  padding: 0 16px;
}

.search-icon {
  margin-right: 12px;
  color: #666;
}

.search-input input {
  flex: 1;
  border: none;
  background: transparent;
  padding: 12px 0;
  font-size: 16px;
  outline: none;
}

.search-btn {
  background: #1976D2;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

/* 位置状态指示器样式 */
.location-status {
  margin-top: 12px;
  padding: 8px 0;
}

.status-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
  gap: 8px;
}

.status-item.loading {
  background: #e3f2fd;
  color: #1976d2;
}

.status-item.success {
  background: #e8f5e8;
  color: #2e7d32;
}

.status-item.error {
  background: #ffebee;
  color: #c62828;
}

.status-item.denied {
  background: #fff3e0;
  color: #ef6c00;
}

.status-icon {
  font-size: 16px;
}

.accuracy-info {
  font-size: 12px;
  opacity: 0.8;
  margin-left: 8px;
}

.refresh-location-btn {
  background: transparent;
  border: 1px solid currentColor;
  border-radius: 4px;
  padding: 2px 8px;
  margin-left: auto;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.refresh-location-btn:hover {
  background: currentColor;
  color: white;
}

/* 地图容器样式 */
.map-container {
  flex: 1;
  position: relative;
  background: #e0e0e0;
}

.amap-container {
  width: 100%;
  height: 100%;
}

/* 地图控制按钮 */
.map-controls {
  position: absolute;
  right: 20px;
  bottom: 100px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  z-index: 1000;
}

.control-btn {
  width: 48px;
  height: 48px;
  background: white;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
}

.control-btn:hover {
  background: #f0f0f0;
  transform: scale(1.05);
}

.control-icon {
  font-size: 20px;
}

.location-btn {
  background: #4CAF50;
  color: white;
}

.location-btn:hover {
  background: #45a049;
}

.refresh-btn {
  background: #2196F3;
  color: white;
}

.refresh-btn:hover {
  background: #1976D2;
}

.info-btn {
  background: #FF9800;
  color: white;
}

.info-btn:hover {
  background: #F57C00;
}

/* 位置信息面板样式 */
.location-info-panel {
  position: absolute;
  left: 20px;
  top: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  width: 280px;
  z-index: 1000;
  max-height: 300px;
  overflow: hidden;
}

.panel-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  background: #f8f9fa;
}

.close-panel {
  cursor: pointer;
  font-size: 18px;
  color: #666;
  transition: color 0.3s;
}

.close-panel:hover {
  color: #333;
}

.panel-content {
  padding: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-weight: 500;
  color: #666;
}

.info-value {
  font-family: 'Courier New', monospace;
  color: #333;
}

.status-success {
  color: #4CAF50;
  font-weight: 500;
}

/* 筛选面板 */
.filter-panel {
  position: absolute;
  right: 20px;
  top: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  width: 280px;
  z-index: 1000;
}

.filter-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-filter {
  cursor: pointer;
  font-size: 18px;
}

.filter-content {
  padding: 16px;
}

.filter-item {
  margin-bottom: 16px;
}

.filter-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.filter-item select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.filter-actions {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  gap: 12px;
}

.filter-actions button {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.filter-actions button:first-child {
  background: #1976D2;
  color: white;
  border-color: #1976D2;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  z-index: 1000;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #fff;
  border-top: 1px solid #eee;
  padding: 0;
}

.nav-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px 0;
  cursor: pointer;
  transition: color 0.2s;
}

.nav-item i {
  font-size: 20px;
  margin-bottom: 4px;
  color: #999;
}

.nav-item span {
  font-size: 12px;
  color: #999;
}

.nav-item.active i,
.nav-item.active span {
  color: #4a90e2;
}

.nav-item.active i {
  background-color: #4a90e2;
  color: white;
  border-radius: 50%;
  padding: 8px;
  margin-bottom: 4px;
}

/* 搜索结果 */
.search-results {
  position: absolute;
  bottom: 80px;
  left: 20px;
  right: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  max-height: 300px;
  overflow-y: auto;
  z-index: 1000;
}

.results-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.close-results {
  cursor: pointer;
  font-size: 18px;
}

.results-list {
  padding: 0 16px;
}

.result-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.result-item:last-child {
  border-bottom: none;
}

.result-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.result-address {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.result-distance {
  font-size: 12px;
  color: #1976D2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    padding: 12px 16px;
  }
  
  .search-bar {
    padding: 12px 16px;
  }
  
  .map-controls {
    left: 16px;
    bottom: 80px;
  }
  
  .filter-panel {
    right: 16px;
    width: 260px;
  }
}
</style>
